package com.mis.pos.service.impl;

import com.mis.pos.dto.ItemNumberDTO;
import com.mis.pos.entity.SaleEntity;
import com.mis.pos.entity.SaleItemEntity;
import com.mis.pos.repository.SaleItemRepository;
import com.mis.pos.repository.SaleRepository;
import com.mis.pos.service.SaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author yuxiang
 * @CreatedDate 2019/11/14 15:57
 */
@Service
public class SaleServiceImpl implements SaleService {

    @Autowired
    private SaleRepository saleRepository;

    @Resource
    private SaleItemRepository saleItemRepository;

    @Override
    public int save(SaleEntity saleEntity) {
        try{
            saleRepository.save(saleEntity);
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }
        return 0;
    }

    @Override
    public int saveSaleItem(List<ItemNumberDTO> dtos, Long saleId) {
        //批量存储的订单商品实体
        List<SaleItemEntity> saleItemEntities = new ArrayList<>();
        //批量存储
        for (ItemNumberDTO dto :
                dtos) {
            saleItemEntities.add(new SaleItemEntity(dto.getItemId(), saleId,dto.getNumber()));
        }
        try {
            saleItemRepository.saveAll(saleItemEntities);
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }
        return 0;
    }

    @Override
    public int updateSaled(Long saleId) {
        try {
            saleRepository.updateSaled(saleId);
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }
        return 0;

    }

    @Override
    public SaleEntity searchBySaleId(Long saleId) {
        return saleRepository.findSaleEntityById(saleId);
    }

    @Override
    public List<SaleEntity> listSale(Integer pageNumber, Integer pageSize) {

        return saleRepository.listSale(pageNumber,pageSize);
    }

    @Override
    public Integer countSales() {
        return Math.toIntExact(saleRepository.count());
    }

    @Override
    public int deletSaleById(Long id) {
        try {
            //1.删除订单记录
            saleRepository.deleteSaleEntityById(id);
            //2.删除sale_item关联表的数据
            saleItemRepository.deleteSaleItemEntitiesBySaleId(id);
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }
        return 0;
    }
}
